<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Cat;
class CatController extends Controller
{
    public function __construct()
    {
        $this->Cat = new Cat();
    }

    /**
     * Display a listing of the resource.
     *栏目显示
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->findAll();
        return view('admin.cat_index')->with('data',$data);
    }

    /**
     * Show the form for creating a new resource.
     *栏目添加显示
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = $this->findAll();
        return view('admin.cat_add')->with('data',$data);
    }

    /**
     * Store a newly created resource in storage.
     *栏目添加操作
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //验证
        $cat = $this->Cat;
        $cat->name = $request->name;
        $cat->pid  = $request->pid;
        $cat->save();
        return redirect('admin/cat');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 找子孙栏目
     * @param $data
     * @param int $id
     * @param int $lev
     */
    public function findTree($data,$id=0,$lev=0)
    {
        static $tree = [];
        foreach($data as $k=>$v){
            if($v['pid'] == $id){
                $v['lev']=$lev;
                $tree[]=$v;
                $this->findTree($data,$v['id'],$lev+1);
            }
        }
        return $tree;
    }

    /**
     * 格式化取出所有栏目
     */
    protected function findAll()
    {
        $cats = Cat::select('name','id','pid')->get();
       return $this->findTree($cats,0,0);
    }

}
